import Taro, { Component } from '@tarojs/taro'
import {View, Text, Image, Button, ScrollView} from '@tarojs/components'
import { connect } from '@tarojs/redux'
import { AtButton, AtIcon, AtCurtain } from 'taro-ui'
import {GoodItem} from '../../components/homeGoodItem/goodItem'
import { asyncLoadHomeDaily, dailyReset } from '../../actions/daily'
import { asyncLoadHomeGroupbuy, groupBuyReset } from '../../actions/groupBuy'
import { asyncShop, updateShop } from '../../actions/shop'
import { asyncWechatCouponA } from '../../actions/reduction'
import { asyncGetUserdVoucher } from '../../actions/voucher'
import { setWxUserInfo, setUserMapPin, asyncUserCheckinInfo, setUserCheckin } from '../../actions/user'
import { setCartBadge } from '../../actions/cart'
import {asyncGetOpenId} from '../../api/user'
import {asyncGetRecommendedShop} from '../../api/shop'
import LoginModal from '../../components/loginModal'
import './index.styl'
import QQMapWX from '../../components/lbs/qqmap-wx-jssdk'
import withShare from '../../components/withShare'
import closePng from '../../assets/images/home/close.png'
import benefitPng from '../../assets/images/hui.png'
import checkinPng from '../../assets/images/checkin.png'

let qqmapsdk
@withShare({})
@connect(({ daily, groupBuy, shop, user,reduction,voucher }) => ({
  daily,
  shop,
  groupBuy,
  user,
  reduction,
  voucher
}), (dispatch) => ({
  // 加载代金券
  onGetUserdVoucher (shop_only = true) {
    dispatch(asyncGetUserdVoucher(shop_only))
  },
  // 加载系统满减
  onUpdateCoupon () {
    dispatch(asyncWechatCouponA())
  },
  
  // 加载店铺信息
  onAsyncShop () {
    dispatch(asyncShop())
  },
  // 加载每日生鲜
  onAsyncDaily () {
    dispatch(asyncLoadHomeDaily())
  },
  // 重置每日生鲜
  onDailyReset () {
    dispatch(dailyReset())
  },
  // 加载社区拼购
  onAsyncGroup () {
    dispatch(asyncLoadHomeGroupbuy())
  },
  // 重置社区拼购
  onGroupReset () {
    dispatch(groupBuyReset())
  },
  // 获取到用户信息时
  onGetWxUserInfo (data) {
    dispatch(setWxUserInfo(data))
  },
  // 获取到用户切换地址时
  onGetUserMapPin(data) {
    dispatch(setUserMapPin(data))
  },
  // 更新推荐店铺的id
  onGetShopID (id) {
    dispatch(updateShop({shop_id: id}))
  },
  // 加载购物车数据
  onSetCartBadge () {
    return dispatch(setCartBadge())
  },
  // 加载用户签到信息
  onUserCheckinInfo () {
    return dispatch(asyncUserCheckinInfo())
  },
  // 关闭签到
  onCloseCheckin () {
    return dispatch(setUserCheckin(false))
  }
}))

class Index extends Component {
  config = {
    navigationBarTitleText: '首页'
  }
  constructor() {
    super(...arguments)
    this.state = {
      showAuthModal: false// 授权弹窗
    }
    this.$app = this.$app || {}
  }
  // 拨打店铺电话
  callShopTel () {
    Taro.makePhoneCall({
      phoneNumber: this.props.shop.tel 
    })
  }
  //跳转惠店订单
  turnBenefit () {
    Taro.navigateTo({
      url: '/pages/benefit/index'
    })
  }
  // 查看全部每日鲜果
  goDailyList () {
    Taro.navigateTo({
      url: '/pages/daily/index'
    })
  }

  // 查看全部社区拼购
  goGroupBuyList () {
    Taro.navigateTo({
      url: '/pages/groupBuy/index'
    })
  }
  //预览参与
  // turnShow () {
  //   Taro.navigateTo({
  //       url: '/pages/groupBuy/show?&scene=6WObBz5Rg3Ra4ycy-29'
  //   })
  // }
  // 处理授权结果
  prcoessAuthResult(user) {
    this.setState({showAuthModal: false})
    const {avatarUrl: avatar, nickName: nickname} = user.userInfo
    const { location } = user
    this.props.onGetWxUserInfo({avatar, nickname}) // 设置到redux中供后续使用
    // 发送注册登录请求
    asyncGetOpenId(user.code, user.location.latitude, user.location.longitude, avatar, nickname).then(({data, status}) => {
      if (status) {
        const {token, openid} = data
        Taro.setStorageSync('token', token)
        Taro.setStorageSync('openid', openid)
        Taro.setStorageSync('userInfo', user.userInfo)
        this.props.onGetWxUserInfo({token, openid}) // 设置到redux中供后续使用
        // this.setState({showAuthModal: false, showAddressModal: true})
        // 定位信息
        this.prcoessAddress(location)
      }
    }).catch(err => console.log(err))
  }
  prcoessAddressAuto () {
    // 查看用户的已授权
    Taro.getSetting({}).then(set => {
      // 如果用户已授权位置信息
      if (set.authSetting['scope.userLocation']) {
        Taro.getLocation({}).then((loc) => {
          this.prcoessAddress(loc)
        })
      } else {
        Taro.authorize({
          scope: 'scope.userLocation'
        }).then(() => {
          Taro.getLocation({}).then((loc) => {
            this.prcoessAddress(loc)
          })
        })
      }
    }).catch(err => console.log(err))

  }

  // 处理用户同意选择地址
  prcoessAddressSelect () {
    // 选择地址
    Taro.chooseLocation({}).then((loc) => {
      this.prcoessAddress(loc)
    })
  }

  reverseGeocoder ({latitude, longitude}) {
    return new Promise((resolve, reject) => {
      qqmapsdk.reverseGeocoder({
        location: {latitude, longitude},
        success (res) {
          if (res.status !== 0) {
            reject(res.status)
          } else {
            resolve({
              address: res.result.address,
              formatted_addresses: res.result.formatted_addresses
            })
          }
        },
        fail () {
          reject()
        }
    })
    })
  }

  async prcoessAddress (loc) {
    let {latitude, longitude, address, name} = loc
    // 如果没有地址的name, 调用腾讯地图api获取
    if (!name) {
      const {address: _address, formatted_addresses} = await this.reverseGeocoder({latitude, longitude})
      address = _address
      name = formatted_addresses.recommend
    }

    Taro.setStorageSync('userPinLocation', JSON.stringify({latitude, longitude, address, name}))
    this.props.onGetUserMapPin({
      latitude, // 经度
      longitude, // 纬度
      address,
      name
    })
    // 发送请求获取推荐店铺
    return asyncGetRecommendedShop(this.props.user.token, loc.latitude, loc.longitude).then(({data, status}) => {
      if (!status) {
        // 没有找到合适店铺的处理
        Taro.showToast({
          title: '抱歉没有合适您的水果店',
          icon: 'none'
        })
        return
      }
      Taro.setStorageSync('shop_id', data.shop_id)
      
      this.props.onGetShopID(data.shop_id)
      this.initShop()
    })
  }


  // 用户点击小区名称，主动切换地址 发起前
  beforeToggleLoction () {
    // 查看用户的已授权
    Taro.getSetting({}).then(set => {
      // 如果用户已授权位置信息
      if (set.authSetting['scope.userLocation']) {
        this.prcoessAddressSelect()
      } else {
        Taro.authorize({
          scope: 'scope.userLocation'
        }).then(() => {
          console.log('用户授权 scope.userLocation')
          this.prcoessAddressSelect()
        })
      }
    }).catch(err => console.log(err))
  }
  // 初始化店铺
  initShop () {
    console.log('initShop')
    
   
    this.props.onUpdateCoupon() // 加载系统满减
    this.props.onAsyncShop() // 加载店铺信息
    this.props.onGetUserdVoucher(true) // 加载代金券
    this.props.onDailyReset() // 重置每日生鲜
    this.props.onAsyncDaily() // 加载每日生鲜

    this.props.onGroupReset() // 重置社区拼购
    this.props.onAsyncGroup() // 加载社区拼购

    this.props.onSetCartBadge() // 加载购物车数量

    this.props.onUserCheckinInfo() // 加载用户签到信息
  }

  // 下拉刷新
  onPullDownRefresh () {
    Taro.stopPullDownRefresh()
    const {token} = this.props.user
    const {shop_id} = this.props.shop
    // 如果没有token,需要弹窗授权
    if (!token) {
      this.setState({showAuthModal: true})
      return
    }
    // 自动定位当前位置
    if (!shop_id) {
      this.prcoessAddressAuto()
      return
    }
    this.initShop()
  }

  // 阻止穿透点击
  onStopClick = (e) => {
    e.stopPropagation()
    e.preventDefault()
  }

  // 去签到
  goCheckin () {
    const {shop_id} = this.props.shop
    this.props.onCloseCheckin()
    Taro.navigateTo({
      url: `/pages/game/minute?type=1&shop_id=${shop_id}`
    })
  }

  // 关闭签到
  closeCheckin () {
    this.props.onCloseCheckin()
  }

  componentWillReceiveProps (nextProps) {
    console.log(nextProps)
  }
  shouldComponentUpdate (nextProps, nextState) {
    // 如果是state引起的，更新
    if (this.state !== nextState) return true
    // 如果是店铺变化引发的 更新
    if (this.props.shop.shop_id !== nextProps.shop.shop_id) return true
    // 如果用户切换地址 更新
    if (this.props.user.location !== nextProps.user.location) return true
    // 如果每日列表变化 更新
    if (this.props.daily.homeList !== nextProps.daily.homeList) return true
    // 如果拼购列表变化 更新
    if (this.props.groupBuy.homeList !== nextProps.groupBuy.homeList) return true
    console.log('不更新')
    return false
  }
  componentDidMount () {
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'SVRBZ-4TXW6-Y7ZSW-ELRLI-2FIWK-XYBQ3'
    });
    const {token} = this.props.user
    const {shop_id} = this.props.shop
    // 如果没有token,需要弹窗授权
    if (!token) {
      this.setState({showAuthModal: true})
      return
    }
    // 自动定位当前位置
    if (!shop_id) {
      this.prcoessAddressAuto()
      return
    }
    this.initShop()
  }
  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  render () {
    const { showAuthModal } = this.state
    const { location } = this.props.user
    const checkin = this.props.user.checkin;
    const dailyHomeList = this.props.daily.homeList

    const renderDailyList = dailyHomeList.slice(0, 6).map((item, index) => {
      return (
        <GoodItem
          key={index}
          goodId={item.id}
          thumb={item.thumb}
          name={item.name}
          tags={item.tags}
          sales={item.month_sale}
          price={item.sale_price}
          sale_price={item.sale_price}
          spec_name={item.spec.name}
          weight={item.weight}
        />
        )
    })
    const groupBuyHomeList = this.props.groupBuy.homeList
    const renderGroupList = groupBuyHomeList.slice(0, 6).map((item, index) => {
      return (
        <GoodItem
          key={index}
          isGroup
          goodId={item.id}
          thumb={item.thumb}
          name={item.name}
          tags={item.tags}
          sales={item.month_sale}
          price={item.group_price}
          sale_price={item.sale_price}
          spec_name={item.spec.name}
          weight={item.weight}
        />
      )
    })

    return (
      <View className='index'>
        {/* 分享按钮 */}
        {/*<Button openType='share' className='share'>*/}
          {/*<AtIcon value='share' size='14' color='#FFF' />*/}
          {/*<Text>分享</Text>*/}
        {/*</Button>*/}
        {/* 店铺信息 */}
        <View className='header'>
          {/*定位信息*/}
          <View className='address' onClick={this.beforeToggleLoction.bind(this)}>
            <AtIcon value='map-pin' size='12' color='#525C6B' />
            <Text className='name'>{location.name || '--'}</Text>
            <AtIcon value='chevron-right' size='12' color='#525C6B' />
          </View>
          <Image src={benefitPng}  className='benefit-logo'  onClick={this.turnBenefit.bind(this)} />
          <Image src={this.props.user.origin + this.props.shop.logo} className='shop-logo' />
          <View className='shop-info'>
            <Text className='shop-name'>{this.props.shop.name}</Text>
            <AtButton type='secondary' size='small' className='shop-tel' onClick={this.callShopTel.bind(this)}>
              <Text className='shopfont shop-phone' />
              <Text>拨打电话</Text>
            </AtButton>
          </View>
          {/* onClick={this.turnShow.bind(this)}  */}
          <View className='shop-notice'>公告：{this.props.shop.notice}</View>
        </View>
        {/* 每日鲜果 */}
        <View className='section'>
          <View className='section-header'>

            <Text className='name'>每日鲜果 <Text className='name-small'> 多买多省 一小时送达</Text></Text>

            <Text className='all' onClick={this.goDailyList.bind(this)}>查看全部</Text>
          </View>
          <ScrollView className='section-list' scrollWithAnimation scrollX>
            <View className='at-row'>
              {renderDailyList}
            </View>
          </ScrollView>
        </View>
        {/* 社区拼购 */}
        <View className='section'>
          <View className='section-header'>
            <Text className='name'>社区拼购 <Text className='name-small'> 找邻居一起买更划算</Text></Text>
            <Text className='all' onClick={this.goGroupBuyList.bind(this)}>查看全部</Text>
          </View>
          <ScrollView className='section-list' scrollWithAnimation scrollX>
            <View className='at-row'>
              {renderGroupList}
            </View>
          </ScrollView>
        </View>
        {/*授权弹窗*/}
        {showAuthModal && <LoginModal
          title='授权提示'
          contentText='需要您登陆授权并允许获得您的位置信息，用以更好的为您推荐精选水果店铺'
          onConfirmCallback={this.prcoessAuthResult.bind(this)}
        />}
        {/*签到弹窗*/}
        {checkin &&
          <View className='checkin-box'>
            <Image
              src={closePng}
              className='checkin-close'
              onClick={this.closeCheckin.bind(this)}
            />
            <Image
              src={checkinPng}
              className='checkin-img'
              onClick={this.goCheckin.bind(this)}
            />
          </View>
        }
      </View>
    )
  }
}

export default Index
